package praca.framework;

import java.io.IOException;

import praca.interfejsy.Game;
import praca.interfejsy.Music;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.MediaPlayer;

public class MusicGL implements Music{

	Game game;
	AssetManager assetManager;
	MediaPlayer mediaPlayer;
	AssetFileDescriptor descriptor = null;
	boolean isPrepared = false;
	
	public MusicGL(Game game){
		this.game = game;
		assetManager = game.getAssetManager();
		mediaPlayer = new MediaPlayer();
		((GameGL)game).setVolumeControlStream(AudioManager.STREAM_MUSIC);
	}
	
	public MusicGL(Game game, String filename){
		this.game = game;
		assetManager = game.getAssetManager();
		mediaPlayer = new MediaPlayer();
		loadMusic(filename);
	}
	
	public void loadMusic(String filename){
		try {
			descriptor = assetManager.openFd(filename);
			mediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(),
					descriptor.getLength());
			mediaPlayer.prepare();
			isPrepared = true;
			mediaPlayer.setLooping(true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException("Nie mozna otworzyc pliku!");
		}
	}
	
	@Override
	public void play() {
		if(game.isSoundEnabled()){
			if(!isPrepared){
				try {
					mediaPlayer.prepare();
					isPrepared = true;
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			while(!isPrepared){}
				
			mediaPlayer.start();
		}
		
		
	}

	@Override
	public void pause() {
		if(game.isSoundEnabled()){
		mediaPlayer.pause();
		isPrepared = true;
		}
	}

	@Override
	public void setLooping(boolean isLooping) {
		if(isLooping)
			mediaPlayer.setLooping(true);
		else
			mediaPlayer.setLooping(false);
		
	}

	@Override
	public void stop() {
		if(game.isSoundEnabled()){
		mediaPlayer.stop();
		isPrepared = false;
		}
	}
	
	public boolean isPlaying(){
		return mediaPlayer.isPlaying();
	}
	
}
